package com.gok.kanmeituyun2.adatper;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.gok.kanmeituyun2.R;
import com.gok.kanmeituyun2.entity.Image;
import com.gok.kanmeituyun2.util.image.ImageUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @Company
 * @Classname
 * @Description TODO  自定义显示图片数据的适配器
 * @Author wbs
 * Date 2021.6.18 14:40
 * Version 1.0
 */
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> {
    //定义监听器对象
    private OnItemClickListener listener;
    //数据
    private List<Image> datas = new ArrayList<>();
    //上下文
    private Context context;
    //填充器
    private LayoutInflater inflater;

    /**
     * @methodName TODO 为适配器设置数据
     *
     * @param datas
     * @author wbs
     * @date 2021.6.18 15:57
     * @return void
     */
    public void setData(List<Image> datas){
        this.datas.clear();
        this.datas.addAll(datas);

        //刷新ImageAdapter 的数据项
        notifyItemRangeRemoved(0,datas.size());
    }

    /**
     * @param context
     * @return
     * @methodName TODO 构造重载
     * @author wbs
     * @date 2021.6.18 14:48
     */
    public ImageAdapter(Context context) {
        this.context = context;
        //将填充器实例化
        this.inflater = LayoutInflater.from(this.context);
    }


    //创建ViewHolder事件
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(inflater.inflate(R.layout.item_image,parent,false));
    }


    //ViewHolder的绑定事件
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.bindData(datas.get(position));

        //要将监听事件绑定到ViewHolder 内部的某个组件上去
        if(holder!=null) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.onClick(position);
                }
            });
        }
    }

    //返回数据的数量
    @Override
    public int getItemCount() {
        return datas.size();
    }


    //自定义的ViewHolder 类
    class ViewHolder extends RecyclerView.ViewHolder {
        private ImageView iv;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            iv = itemView.findViewById(R.id.iv);
        }

        //给iv 绑定数
        public void bindData(Image image){
            //显示这张图片
            ImageUtil.show((Activity) context,image.getUrl(),iv);
        }
    }

    //设置监听器方法
    public void setOnItemClickListener(OnItemClickListener listener){
        this.listener = listener;
    }


    //定义此适配器的监听器
    public interface OnItemClickListener{
        void onClick(int position);
    }

}
